<template>
    <div>
        <!--面包屑导航区域-->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!--卡片视图区-->
        <el-card class="box-card">
            <!--搜索与添加区域-->
            <el-row :gutter="20">
                <el-col :span="10">
                    <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
                        <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4">
                    <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
                </el-col>
            </el-row>

            <!--用户列表区域-->
            <el-table :data="userlist" border stripe>
                <el-table-column type="index"></el-table-column>
                <el-table-column prop="username" label="姓名" ></el-table-column>
                <el-table-column prop="email" label="邮箱" ></el-table-column>
                <el-table-column prop="mobile" label="电话"></el-table-column>
                <el-table-column prop="role_name" label="角色" ></el-table-column>
                <el-table-column prop="mg_state" label="状态" >
                    <template v-slot="scope">
                        <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180">
                    <template v-slot="scope">
                        <el-tooltip effect="dark" content="修改角色" placement="top" :enterable="false">
                            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
                        </el-tooltip>
                        <el-tooltip effect="dark" content="删除角色" placement="top" :enterable="false">
                            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)"></el-button>
                        </el-tooltip>
                        <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
                            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRoleDialog(scope.row)"></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>

            <!--分页-->
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="queryInfo.pagenum"
                    :page-sizes="[1, 2, 5, 10]"
                    :page-size="queryInfo.pagesize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </el-card>
        <!--添加用户对话框-->
    <el-dialog
            title="添加用户"
            :visible.sync="addDialogVisible"
            width="50%" @close="addDialogClosed">
        <el-form :model="newuser" :rules="newuserRules" ref="newuserRef" label-position="right" label-width="65px">
            <el-form-item prop="username" label="用户名">
                <el-input v-model="newuser.username"></el-input>
            </el-form-item>
            <el-form-item prop="password" label="密码">
                <el-input type="password" v-model="newuser.password"></el-input>
            </el-form-item>
            <el-form-item prop="email" label="邮箱">
                <el-input v-model="newuser.email"></el-input>
            </el-form-item>
            <el-form-item prop="mobile" label="手机">
                <el-input v-model="newuser.mobile"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="addDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="adduser(newuser)">确 定</el-button>
        </span>
    </el-dialog>

        <!--修改用户基本信息对话框-->
    <el-dialog
            title="修改用户"
            :visible.sync="editDialogVisible"
            width="50%" @close="editDialogClosed">
        <el-form :model="editForm" :rules="editUserRules" ref="editUserRef" label-position="right" label-width="65px">
        <el-form-item label="用户名">
            <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="editForm.email"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="mobile">
                <el-input v-model="editForm.mobile"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="edituser(editForm)">确 定</el-button>
        </span>
    </el-dialog>

        <!--分配用户角色对话框-->
        <el-dialog
                title="提示"
                :visible.sync="setRolesDialogVisible"
                width="50%"
                @close="setRoleDialogClosed">
            <el-row>
                <span>当前用户是： {{currentuser.username}}</span>
            </el-row>
            <el-row>
                <span>当前角色是： {{currentuser.role_name}}</span>
            </el-row>
            <el-row>
                <span>分配新角色：</span>
                <el-select v-model="selectRoleId" placeholder="请选择">
                <el-option
                        v-for="item in rolesList"
                        :key="item.id"
                        :label="item.roleName"
                        :value="item.id">
                </el-option>
            </el-select>

            </el-row>
            <span slot="footer" class="dialog-footer">
    <el-button @click="setRolesDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="setRole">确 定</el-button>
  </span>
        </el-dialog>
    </div>
</template>

<script>

    export default {
        name: "Users",

        data(){
            var checkEmail = (rule,value,callback) => {
                const regEmail = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/
                if(regEmail.test(value) == true){
                    return callback()
                }
                callback(new Error('请输入合法的邮箱'))
            }
            var checkMobile = (rule,value,callback) => {
                const regMobile = /^1[3456789]d{9}$/
                if(regMobile.test(value) == true){
                    return callback()
                }
                callback(new Error('请输入合法的手机号'))
            }
            return{
                queryInfo:{
                    query:'',
                    pagenum: 1,
                    pagesize: 2
                },
                userlist:[],
                total:0,
                addDialogVisible: false,
                editDialogVisible:false,
                setRolesDialogVisible:false,
                newuser:{
                    username:'',
                    password:'',
                    email:'',
                    mobile:''
                },
                editForm:{
                    id:'',
                    mobile:'',
                    email:''
                },
                newuserRules:{
                    username:[
                        {required:true,message:'请输入用户名',trigger:'blur'},
                        {min:3,max:10,message: '长度在3到10之间',trigger:'blur'}
                        ],
                    password:[
                        {required:true,message:'请输入密码',trigger:'blur'},
                        {min:6,max:15,message: '长度在8到15之间',trigger:'blur'}
                        ],
                    email:[
                        {required:true,message:'请输入邮箱',trigger:'blur'},
                        {validator: checkEmail,trigger:'blur'}
                    ],
                    mobile:[
                        {required:true,message:'请输入手机号',trigger:'blur'}
                        //{validator: checkMobile,trigger:'blur'}
                    ]
                },
                editUserRules:{
                    email:[
                        {required:true,message:'请输入邮箱',trigger:'blur'},
                        {validator: checkEmail,trigger:'blur'}],
                    mobile:[
                        {required:true,message:'请输入手机号',trigger:'blur'}
                        //{validator: checkMobile,trigger:'blur'}
                    ]
                },
                //角色列表
                rolesList:[],
                //点击分配角色后保存的当前用户
                currentuser:'',
                //分配角色中下拉列表的选中项
                selectRoleId:''
            }

        },
        created() {
            this.getUserList()
        },
        methods:{
            //获取用户列表函数
            async getUserList(){
              const {data:res} =  await this.$http.get('users',{params:this.queryInfo })
                //console.log(res)
                if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
                this.userlist = res.data.users
                this.total=res.data.total
            },
            //每页显示条数改变
            handleSizeChange(newSize){
                this.queryInfo.pagesize = newSize
                this.getUserList()
            },
            //当前页改变
            handleCurrentChange(newPage){
                this.queryInfo.pagenum = newPage
                this.getUserList()
            },
            //修改用户状态
            async userStateChange(userinfo){
                console.log(userinfo)
                const {data:res} = await this.$http.put(`/users/${userinfo.id}/state/${userinfo.mg_state}`,)
                if(res.meta.status !== 200) {
                    userinfo.mg_state = !userinfo.mg_state
                    return this.$message.error('修改状态失败')
                }
                this.$message.success('修改状态成功')
            },
            //添加用户
            adduser(newuser){
                this.$refs.newuserRef.validate(async (valid)=>{
                    if (!valid){
                        this.$refs.newuserRef.resetFields();
                        return
                    }
                    const {data:res} = await this.$http.post('/users',this.newuser)
                    if(res.meta.status !== 201) return this.$message.error('添加用户失败！');
                    this.getUserList()
                    this.$message.success('添加用户成功！')
                    this.addDialogVisible = false;

                })
            },
            //关闭添加用户对话框
            addDialogClosed(){
                this.$refs.newuserRef.resetFields();
            },
            //显示修改用户对话框，通过id查询用户信息
            async showEditDialog(id){
                this.editDialogVisible = true

                const {data:res} = await this.$http.get(`/users/${id}`)
                //console.log(res)
                if  (res.meta.status !== 200){
                    return this.$message.error('查询用户信息失败')
                }
                this.editForm = res.data

            },
            //修改用户信息
            edituser(editForm){
                this.$refs.editUserRef.validate(async (valid)=>{
                    if(!valid){
                        return
                    }
                    const {data:res} = await this.$http.put(`/users/${editForm.id}`,editForm)
                    if(res.meta.status !== 200) return this.$message.error("修改用户失败")
                    this.editDialogVisible = false
                    this.getUserList()
                    this.$message.success("修改用户成功")
                })
            },
            //关闭修改用户对话框,清除验证效果
            editDialogClosed(){
                this.$refs.editUserRef.resetFields();
            },
            //删除用户信息
            async removeUserById(id){
                //用户点击确认，返回字符串confirm
                //用户点击取消，返回字符串cancel
                const res =await this.$confirm('此操作将永久删除该用户信息, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).catch(err => err)
                if(res !== 'confirm') return this.$message.info('已取消操作')
                const {data:result} = await this.$http.delete('/users/'+id)
                console.log(result)
                if(result.meta.status !== 200) return this.$message.error('删除失败')
                this.getUserList()
                this.$message.success('删除成功')

            },
            //显示分配角色对话框
            async showSetRoleDialog(user){
                this.setRolesDialogVisible = true
                this.currentuser = user
                //console.log(user)
                //获取角色列表
               const {data:res}=await this.$http.get('/roles')
                if(res.meta.status !== 200) return this.$message.error("获取角色列表失败")
                this.rolesList = res.data
                console.log(this.rolesList)
            },
            //分配角色
            async setRole(){
                if(!this.selectRoleId) return this.$message.error("请选择角色")
                const{data:res} = await this.$http.put(`/users/${this.currentuser.id}/role`,{rid:this.selectRoleId})
                if(res.meta.status !== 200) return this.$message.error("分配角色失败")
                this.$message.success("分配角色成功")
                this.getUserList()
                this.setRolesDialogVisible = false
            },
            setRoleDialogClosed(){
                this.selectRoleId = ''
                this.currentuser = {}
            }
        }
    }
</script>

<style lang="less" scoped>

</style>
